import {
	baseURL
} from './config.js'
// uni.request封装
export const request = (opts) => {
	let data = opts.data || {}
	const query = opts.query || false
	let url = baseURL + opts.url
	let params = {}
	for (let key in data) {
		if (data[key] === 0) {
			params[key] = data[key]
		} else {
			if (data[key]) {
				params[key] = data[key]
			}
		}
	}
	
	if(query){
		let parameter = Object.keys(params).map(key => key + "=" + params[key]).join("&");
		url = `${url}?${parameter}`
	}
	
	let defaultOpts = {
		header: opts.header ? {
			...opts.header,
			'Authorization': uni.getStorageSync('token') ||
				''
		} : {
			'Content-type': 'application/json;charset=UTF-8',
			'Authorization': uni.getStorageSync('token') ||
				''
		},
		url,
		method: opts.method || 'GET',
		dataType: opts.dataType || 'json',
		data: params
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(defaultOpts)
			.then((response) => {
				if (response[1].data.code == 1000 ) {
					resolve(response[1].data)
				} else if (response[1].data.code == 401) {
					uni.clearStorageSync();
					uni.showToast({
						icon: 'none',
						title: '登录过期,请重新登录。',
						duration: 2000
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/login'
						})
					}, 1500)
				} else {
					uni.showToast({
						icon: 'none',
						title: response[1].data.msg,
						duration: 2000
					});
				}

			})
			.catch((error) => {
				// reject(error)
				uni.showToast({
					icon: 'none',
					title: '网络错误,请稍后重试!',
					duration: 2000
				});
			})
	})

	return promise
}
